package com.vogue.supplymall.common.domain.tool;

import com.vogue.ssm.database.entity.SnowflakeIdWorker;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * The type Order number generator.
 *
 * @aouthor: zhangliang
 * @date: Create in 2018-01-23
 */
public class OrderNumberGenerator {

	/**
	 * 单据编号类型
	 * 
	 * @author 崔岳
	 *
	 */
	public enum EnumOrderNumberType {
		/** 订单 */
		ORDER(11),
		/** 退单 */
		BACK(12),
        /** 退单 */
        MANAGEMENT(21);

		private int tCode;

		private EnumOrderNumberType(int tCode) {
			this.tCode = tCode;
		}

		public String toString() {
			return String.valueOf(this.tCode);
		}
		
		public int getCode() {
	        return tCode;
	    }
	};
    /** 上次生成ID的时间截 */
    private static long lastTimestamp = -1L;
    
    /** 毫秒内序列(0~4095) */
    private static long sequence = 0L;
    
    /** 序列在id中占的位数 */
    private final static long sequenceBits = 12L;
    
    /** 生成序列的掩码，这里为4095 (0b111111111111=0xfff=4095) */
    private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
    
    private static DecimalFormat df=(DecimalFormat)NumberFormat.getInstance();

    private static SimpleDateFormat formatter = new SimpleDateFormat("yyMMddHHmmssSSS");
    /**
     * 默认生成订单的编号
     * 
     * @return
     */
    public synchronized static String getter() {
    	return getter(EnumOrderNumberType.ORDER);
    }
    
	// ==============================Methods==========================================
    /**
     * 获得一个订单编号 (该方法是线程安全的)
     * @param 订单类型(10订单  11退单)
     * @return OrderNumber 一般返回22位最多25位 组成：类型编号(10)+日期(yyMMdd)+时间(HHmmss)+毫秒(SSS)+机器码(XX)+服务码(XX)+毫秒内序列(0~4095)
     */
    public synchronized static String getter(EnumOrderNumberType type) {

        long timestamp = timeGen();

        //如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        //如果是同一时间生成的，则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            //毫秒内序列溢出
            if (sequence == 0) {
                //阻塞到下一个毫秒,获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        }
        //时间戳改变，毫秒内序列重置
        else {
            sequence = 0L;
        }

        //上次生成ID的时间截
        lastTimestamp = timestamp;
    	
    	df.applyPattern("00");    	
    	Date date = new Date(lastTimestamp);
    	String formatStr =formatter.format(date);
    	
        return type.toString() + formatStr 
        		+ df.format(SnowflakeIdWorker.serno) 
        		+ df.format(SnowflakeIdWorker.dsno) 
        		+ sequence;
    }

    /**
     * 阻塞到下一个毫秒，直到获得新的时间戳
     * @param lastTimestamp 上次生成ID的时间截
     * @return 当前时间戳
     */
    protected static long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 返回以毫秒为单位的当前时间
     * @return 当前时间(毫秒)
     */
    protected static long timeGen() {
        return System.currentTimeMillis();
    }

}
